package code.codeworld.common.kits;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.thymeleaf.util.ArrayUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * @Description: 请求部件
 * @Author: codeworld
 * @Date: 2023/5/23-16:22
 * @version: 1.0
 */
@Slf4j
public class Request {

    /*网页端请求路径*/
    public static final String CODEWORLD_WEB = "/codeworld/web/";

    /*获取请求IP*/
    public static String getIpAddress(HttpServletRequest request) {
        String sourceIp = null;

        String ipAddresses = request.getHeader("x-forwarded-for");

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getRemoteAddr();
        }
        if (!StringUtils.isEmpty(ipAddresses)) {
            sourceIp = ipAddresses.split(",")[0];
        }

        return sourceIp;
    }


    /**
     * 根据IP地址获取地理位置
     */
    public static String getAddressByIP(String ip) {
        ip = "114.103.58.245";
        // 实时查询 太平洋网站api
        final String ADDRESS_URL = "https://whois.pconline.com.cn/ipJson.jsp";
        final String UNKNOWN = "未知";
        final String[] LOCAL_IP_ARRAY = new String[]{"127.0.0.1", "0:0:0:0:0:0:0:1"};
        if (ObjectUtils.isEmpty(ip)) {
            return "";
        }
        if (ArrayUtils.contains(LOCAL_IP_ARRAY, ip)) {
            return "局域网，无法获取位置";
        }

        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("ip", ip);
            paramMap.put("json", true);
            String response = HttpUtil.get(ADDRESS_URL, paramMap);
            if (ObjectUtils.isEmpty(response)) {
                log.error("根据IP获取地址异常 {}", ip);
                return UNKNOWN;
            }

            Address address = JSONObject.parseObject(response, Address.class);
            return String.format("%s %s", address.getPro(), address.getCity());
        } catch (Exception e) {
            log.error("根据IP获取地址异常 {}", ip);
        }

        return UNKNOWN;
    }

    @Data
    static class Address {
        /**
         * 省
         */
        private String pro;
        /**
         * 市
         */
        private String city;
    }

    /**
     * 根据IP地址获取地理位置
     */
    public static String getAddressByIP_bak(String ip) {
        ip = "114.103.58.245";
        final String API_URL = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6006&format=json&query=";
        final String[] LOCAL_IP_ARRAY = new String[]{"127.0.0.1", "0:0:0:0:0:0:0:1"};
        if (ObjectUtils.isEmpty(ip)) {
            return "";
        }
        if (ArrayUtils.contains(LOCAL_IP_ARRAY, ip)) {
            return "局域网，无法获取位置";
        }
        String url = API_URL + ip;
        HttpResponse res = HttpRequest.get(url).execute();
        if (200 != res.getStatus()) {
            return "获取位置失败";
        } else {
            JSONObject resJson = JSONObject.parseObject(res.body());
            JSONArray resArr = JSONArray.parseArray(resJson.getString("data"));
            resJson = JSONObject.parseObject("" + resArr.get(0));
            return resJson.getString("location");
        }
    }
}
